<script setup>
import { ref } from 'vue';
import { useRouter } from 'vue-router';
import http from '@/utils/api.js';

const router = useRouter();

// 表单数据模型
const product = ref({
  name: '',
  price: 0,
  stock: 0,
});

// 提交表单数据到后端
const handleSubmit = async () => {
  try {
    if (!product.value.name || product.value.price <= 0 || product.value.stock < 0) {
      alert('请填写完整的商品信息');
      return;
    }

    const response = await http.post('/product/add', product.value); // 提交数据到后端
    console.log(response.data);
    if (response.code === 200) {
      alert('商品添加成功');
      await router.push('/dashboard'); // 添加成功后跳转回商品列表页面
    } else {
      alert(response.data.message || '添加失败');
    }
  } catch (error) {
    console.error('添加商品失败:', error);
    alert('商品添加失败，请检查网络或后端服务！');
  }
};
</script>

<template>
  <div class="form-container">
    <el-form :model="product" ref="form" label-width="120px" class="product-form">
      <el-form-item label="商品名称">
        <el-input v-model="product.name" placeholder="请输入商品名称"/>
      </el-form-item>
      <el-form-item label="价格">
        <el-input type="number" v-model="product.price" placeholder="请输入商品价格"/>
      </el-form-item>
      <el-form-item label="库存">
        <el-input type="number" v-model="product.stock" placeholder="请输入商品库存"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSubmit" class="submit-button">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<style scoped>
.form-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  border-radius: 8px;
}

.product-form {
  width: 100%;
}

.el-form-item {
  margin-bottom: 20px;
}

.el-form-item label {
  font-size: 14px;
  color: #333;
}

.el-input {
  width: 100%;
  max-width: 400px;
  border-radius: 4px;
  padding: 8px 12px;
}

.el-button.submit-button {
  width: 100%;
  padding: 10px 0;
  font-size: 16px;
  background-color: #409EFF;
  border-color: #409EFF;
  color: white;
  border-radius: 4px;
}

.el-button.submit-button:hover {
  background-color: #66b1ff;
  border-color: #66b1ff;
}

.el-button.submit-button:active {
  background-color: #338dff;
  border-color: #338dff;
}
</style>
